<?php
	class Respondents extends Controller{
		/*
		 * Constructor
		 *
		 * Parameter:
		 * none
		 *
		 * Return Value:
		 * none
		 */
		function Respondents(){
			parent::Controller();
		}
		
		
		/*
		 * Redirects to the gate controller
		 *
		 * Parameter:
		 * none	
		 * 
		 * Return Value:
		 * none
		 */
		function index(){
			redirect('gate');	
		}		
		
		
		/*
		 * Loads the survey form and records the validated answers of respondents
		 *
		 * Parameter:
		 * none	
		 * 
		 * Return Value:
		 * none
		 */
		function respond(){
			$data = array();
			$link = $this->uri->segment(3);
			$valid = false;
			
			if($this->Respondent->isValidLink($link)==FALSE)
			{
				echo "<script>javascript:alert('Invalid link!'); window.location = 'http://localhost/pollwatcher/index.php/gate'</script>";
			}
			
			else if($this->Respondent->approvedRSVP($link)==FALSE)
			{
				echo "<script>javascript:alert('You are not eligible to answer this survey.'); window.location = 'http://localhost/pollwatcher/index.php/gate'</script>";
			}
			
			
			else if($this->Respondent->hasAnswered($link) == TRUE)
			{
				echo "<script>javascript:alert('You have already answered this survey!'); window.location = 'http://localhost/pollwatcher/index.php/gate'</script>";
			}
		
			else
			{
			
				$dates = $this->Respondent->getSurveyDate($this->Respondent->getSurveyId($link));
			
				$date_parts1 = explode("-", $dates['begin_date']);
				$date_parts2 = explode("-", date("Y-m-d"));
				$start_date = gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
				$end_date = gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
				$valid_start = $end_date - $start_date;
			
				$date_parts1 = explode("-", date("Y-m-d"));
				$date_parts2 = explode("-", $dates['end_date']);
				$start_date = gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
				$end_date = gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
				$valid_end = $end_date - $start_date;
			
				if($valid_start < 0)
				{
					echo "<script> javascript:alert('Survey has yet to start on ".$dates['begin_date']."'); window.location = 'http://localhost/pollwatcher/index.php/gate'</script>";	
				}
			
				else if($valid_end < 0)
				{
					echo "<script>javascript:alert('Survey has already ended last ".$dates['end_date']."'); window.location = 'http://localhost/pollwatcher/index.php/gate'</script>";	
				}
				
				else
				{
					$valid = true;
				}
			}
			
			if($valid == true)
			{
				$data = $this->Respondent->fetchQuestions($link);
				$data['categories'] = $this->Respondent->getCategories($this->Respondent->getSurveyId($link));
				$data['description'] = $this->Respondent->getSurveyDescription($this->Respondent->getSurveyId($link));
				$data['regions'] = $this->Respondent->getRegions();
				$data['provinces'] = $this->Respondent->getProvinces();
				$data['cities'] = $this->Respondent->getCities();
			
			
				$this->load->library('formdate');
				$formdate = new FormDate(); 
				$formdate->setLocale('nl_BE');
				$formdate->year['start'] = 1900;
				$formdate->year['end'] = 2011;
				$data['formdate'] = $formdate;
				$data['link'] = $link;			
			
				$required_fields = $this->Respondent->getRequiredFields($this->Respondent->getSurveyId($link));
				$data['firstname'] = $required_fields['firstname'];
				$data['middlename'] = $required_fields['middlename'];
				$data['lastname'] = $required_fields['lastname'];
				$data['gender'] = $required_fields['gender'];
				$data['birthday'] = $required_fields['birthday'];
				$data['location'] = $required_fields['location'];
						
				$rules = array();
				$rules['firstname'] = ($required_fields['firstname']!=FALSE) ? "required|callback_alpha_space" : "";
				$rules['middlename'] = ($required_fields['middlename']!=FALSE) ? "required|callback_alpha_space" : "";
				$rules['lastname'] = ($required_fields['lastname']!=FALSE) ? "required|callback_alpha_space" : "";
				$rules['gender'] = ($required_fields['gender']!=FALSE) ? "required" : "";
				$rules['month'] = ($required_fields['birthday']!=FALSE) ? "required" : "";
				$rules['day'] = ($required_fields['birthday']!=FALSE) ? "required" : "";
				$rules['year'] = ($required_fields['birthday']!=FALSE) ? "required|callback_valid_date" : "";			
				$rules['country'] = ($required_fields['location']!=FALSE) ? "required" : "";
				$rules['region'] = ($this->input->post("country") != "Others" && $required_fields['location']!=FALSE) ? "required" : "";
				$rules['province'] = ($this->input->post("country") != "Others" && $required_fields['location']!=FALSE) ? "required" : "";
				$rules['city'] = ($this->input->post("country") != "Others" && $required_fields['location']!=FALSE) ? "required" : "";
				$rules['others'] = ($this->input->post("country") == "Others" && $required_fields['location']!=FALSE) ? "required" : "";
			
				$fields = array();
				$fields['firstname'] = "First Name";
				$fields['middlename'] = "Middle Name";
				$fields['lastname'] = "Last Name";
				$fields['gender'] = "Gender";
				$fields['month'] = "Month";
				$fields['day'] = "Day";
				$fields['year'] = "Year";			
				$fields['country'] = "Country";
				$fields['region'] = "Region";
				$fields['province'] = "Province";
				$fields['city'] = "City";
				$fields['others'] = "Location";
			
				$number = array();
				$type = array();
				$null = array();
				$with_text = array();
				$expected_type = array();
			
				foreach($data['questions'] as $item)
				{
					$number[] = $item['question_number'];
					$type[] = $item['type'];
					$null[] = $item['null_field'];
					$with_text[] = $item['with_text'];
					$expected_type[] = $item['required'];
				}
			
				for($i=0; $i<sizeof($number); $i++)
				{
					$fields["question".$number[$i]] = "Question ".$number[$i]; 
				
					if($type[$i] == "checkboxes")
					{
						$fields["question".$number[$i]] = "Question ".$number[$i]; 
						$rules["question".$number[$i]] = "required";
					}
				
					else if($type[$i] == "ranking")
					{
						for($j=1; $j<=$this->Respondent->getNumChoices($this->Respondent->getSurveyId($link), $number[$i]); $j++)
						{
							$fields["question".$number[$i].$j] = "Question ".$number[$i]." Item ".$j; 
							$rules["question".$number[$i].$j] = "required";
						}
					}
									
					else if($null[$i] == 1)
					{
						$rules["question".$number[$i]] = "required";	
					}
				
					if($with_text[$i] == 1)
					{
						$fields["text".$number[$i]] = "Text for Question ".$number[$i];
						if($expected_type== 1)
						{
							$rules["text".$number[$i]] = "numeric";
						}
					
					}
				}
			
				$this->validation->set_rules($rules);
				$this->validation->set_error_delimiters('<div id="error">', '</div>');
				$this->validation->set_fields($fields);
				$this->validation->set_message('alpha_space', 'The %s field should only contain valid characters');
					
				if ($this->validation->run()==TRUE){
					if($required_fields['firstname']!=FALSE)
						$new['firstname'] = $this->input->post('firstname');
					if($required_fields['middlename']!=FALSE)
						$new['middlename'] = $this->input->post('middlename');
					if($required_fields['lastname']!=FALSE)
						$new['lastname'] = $this->input->post('lastname');
					if($required_fields['gender']!=FALSE)
						$new['gender'] = $this->input->post('gender');		
					if($required_fields['birthday']!=FALSE)
						$new['birthday']= date("Y-m-d", mktime(0,0,0,$this->input->post('month'),$this->input->post('day'),$this->input->post('year')));
				
					if($required_fields['location']!=FALSE)
					{		
						$new['country'] = $this->input->post('country');	
						$new['region'] = $this->input->post('region');
						$new['province'] = $this->input->post('province');
						$new['city'] = $this->input->post('city');
						$new['others'] = $this->input->post('others');
					}
				
					$new['status'] = "done";

					$this->Respondent->updateRespondent($new, $link);
						
					for($i=0; $i<sizeof($number); $i++)
					{
						$new = array();
						$new['respondent_number'] = $this->Respondent->getRespondentNumber($link);
						$new['survey_id'] = $this->Respondent->getSurveyId($link);
						$new['question_number'] = $number[$i];
						if($type[$i] == "checkboxes")
						{
							$checkboxes = $this->input->post("question".$number[$i]); 
							for($j = 0; $j < sizeof($checkboxes) - 1 ; $j++) 
							{
								$new['body'] = $checkboxes[$j];
								$this->Respondent->insertAnswer($new);
							}
							if($with_text[$i] == TRUE)
                            {
                            	$new['explanation'] = $this->input->post("text".$number[$i]);
                            }
                            $new['body'] = $checkboxes[sizeof($checkboxes) - 1];
                            $this->Respondent->insertAnswer($new);
						}
						else if($type[$i] == "ranking")

						{
							for($j=1; $j< $this->Respondent->getNumChoices($this->Respondent->getSurveyId($link), $number[$i]) ; $j++)
							{
								$new['body'] = $this->input->post("question".$number[$i].$j);
								$this->Respondent->insertAnswer($new);
							}
							
							if($with_text[$i] == TRUE)
                           	{
                           		$new['explanation'] = $this->input->post("text".$number[$i]);
                           	}
                           	$new['body'] = $this->input->post("question".$number[$i].$j);
                           	$this->Respondent->insertAnswer($new);					
						}
						else
						{
							$new['body'] = $this->input->post("question".$number[$i]);
							if($with_text[$i] == TRUE)
							{
								$new['explanation'] = $this->input->post("text".$number[$i]);
							}
							$this->Respondent->insertAnswer($new);
						}
					
					}
					echo "<script>javascript:alert('Thank you! Your answer has been successfully recorded.'); window.location = 'http://localhost/pollwatcher/index.php/gate'</script>";
				}
			}
			$gate['body'] = $this->load->view('respondent/respond', $data, TRUE);
			$this->load->view('respondent/main',$gate);
		}
		
		/*
		 * Loads the invite
		 *
		 * Parameter:
		 * none	
		 * 
		 * Return Value:
		 * none
		 */
		function rsvp(){
			$data=array();
			$data['link'] = $this->uri->segment(3);
	
			if($this->Respondent->isValidLink($data['link'])==FALSE)
			{
				
				echo "<script> javascript:alert('Invalid link!'); window.location = 'http://localhost/pollwatcher/index.php/gate'</script>";
			}
			
			else if($this->Respondent->hasResponded($data['link'])==TRUE && $this->Respondent->approvedRSVP($data['link'])==FALSE)
			{
				echo "<script> javascript:alert('You have already rejected this invite!'); window.location = 'http://localhost/pollwatcher/index.php/gate'</script>";
			}
			
			else if($this->Respondent->hasResponded($data['link'])==TRUE && $this->Respondent->approvedRSVP($data['link'])==TRUE)
			{
				echo "<script> javascript:alert('You have already accepted this invite. We are now taking you to the survey form...'); window.location = 'http://localhost/pollwatcher/index.php/respondents/respond/".$data['link']."'</script>";
			}
			$data['body'] = $this->Respondent->getInviteBody($data['link']);
			$gate['body'] = $this->load->view('respondent/rsvp', $data, TRUE);
			$this->load->view('respondent/main', $gate);
		}
		
		/*
		 * Records a respondent's response to an invite
		 *
		 * Parameter:
		 * none	
		 * 
		 * Return Value:
		 * none
		 */
		function submit(){
			$response = $this->input->post('response');
			$this->Respondent->update($response, $this->input->post('link'));
				
			if($response=="YY")
			{
				redirect("respondents/respond/".$this->input->post('link'));
			}
			
			redirect('gate');		
		}
			
		/*
		 * Validates a string input such that it should only contain letters and spaces
		 *
		 * Parameter:
		 * $str		the string of interest	
		 * 
		 * Return Value:
		 * returns true of the string is valid, false otherwise
		 */		
		function alpha_space($str)
		{
			return ( ! preg_match("/^([a-z])+$/i", $str)) ? (preg_match("/\\s/", $str)? TRUE :FALSE) : TRUE;
		}
		
		/*
		 * Records and sends invitations for respondents
		 *
		 * Parameter:
		 * none	
		 * 
		 * Return Value:
		 * none
		 */		
		function invite_resp(){
			$data = array();
			$new['survey_id'] = $this->input->post('survey_id');
			$rules = array();
			$rules['invite_resp'] = "required|valid_emails|callback_already_sent";
			$rules['welcome_message'] = "required";
			
			$this->validation->set_rules($rules);
			$this->validation->set_error_delimiters('<div id="error">', '</div>');
			$fields = array();
			$fields['invite_resp'] = 'Respondents\' Emails';
			$fields['welcome_message'] = 'Invite Message';
			
			$this->validation->set_fields($fields);
			if ($this->validation->run()==TRUE){
				$emails = explode(",", $this->input->post('invite_resp'));
				foreach($emails as $email)
				{
					$temp = array( array( 'column' => 'email','value'=>trim($email) ), array( 'column' => 'survey_id', 'value' => $new['survey_id']));
					
					if(!$this->Respondent->exists('invitation',$temp))
					{
						do
						{	
							$new['link'] = random_string('unique');
						}while($this->Respondent->exists('invitation', array( array( 'column' => 'link', 'value' => $new['link']))));
						$new['body'] = ($this->input->post('welcome_message'));
						$this->Respondent->insertInvite($new['survey_id'], nl2br($new['body']), $new['link'], trim($email));
					
						$config = Array(
						  'protocol' => 'smtp',
						  'smtp_host' => 'ssl://smtp.googlemail.com',
						  'smtp_port' => 465,
						  'esmtp_user' => 'pollwatcher.god@gmail.com',
						  'smtp_pass' => 'ichigokurakurasakiU',
						);
						$this->load->library('email', $config);
						$this->email->set_newline("\r\n");

						$this->email->from('pollwatcher.god@gmail.com', 'PollWatcher');
						$this->email->to(trim($email));

						$new['firstname'] = $this->session->userdata('firstname');
						$new['lastname'] = $this->session->userdata('lastname');
						
						$this->email->subject($this->session->userdata('firstname')." ".$this->session->userdata('lastname')." invites you to answer ".($this->session->userdata('gender')=="Male" ? "his" : "her")." survey");
						
						$this->email->message($this->load->view('invitation', $new, TRUE));
						if (!$this->email->send())
							show_error($this->email->print_debugger());
						
					}
					
				}
				echo "<script> javascript:alert('Invitations successfully sent!');'</script>";
			}
			$data = array();
			$data['survey_id'] = $new['survey_id'];
			$data['id'] = $this->session->userdata('id');
			$data['templates'] = array();
			if ($handle = opendir('templates/invitation')) {
				
				while (false !== ($file = readdir($handle))) {
					if (substr($file, -4) == '.txt') {
						$data['templates'][] = file_get_contents('templates/invitation/'.$file);
					}
					
				}

				closedir($handle);
			}
			$gate['body'] = $this->load->view('user/invite_resp',$data, TRUE);
			$this->load->view('main', $gate);
		}
		
		/*
		 * Checks if the birthday field input is a valid date
		 *
		 * Parameter:
		 * none	
		 * 
		 * Return Value:
		 * true if the date is valid, false otherwise
		 */		
		function valid_date()
		{
			if (!checkdate($this->input->post('month'), $this->input->post('day'), $this->input->post('year')))
			{
				$this->validation->set_message('valid_date', 'The Birthday field is invalid.');
				return FALSE;
			}
			
			return TRUE;
		}
		
		/*
		 * Sends scheduled notifications for respondents who have not answered the survey
		 *
		 * Parameter:
		 * none	
		 * 
		 * Return Value:
		 * none
		 */		
		function notify()
		{
			$notify = $this->Respondent->getUnanswered();
			for($i = 0; $i < sizeof($notify) ; $i++)
			{
				$notif_sched = $this->Respondent->getNotifSched($notify[$i]['survey_id']); 
				
				$dates = $this->Respondent->getSurveyDate($notify[$i]['survey_id']); 	
		
				$now = time();
				$unix_date = strtotime($dates['begin_date']);

				if($now > $unix_date)
				{
					$difference = $now - $unix_date;
				}

				$diff =  floor($difference/(60*60*24));
				
				$now = time();
				$unix_date = strtotime($dates['end_date']);

				$ended = FALSE;
				if($now > $unix_date)
				{
					$ended = TRUE;
				}

				$diff =  floor($difference/(60*60*24));
				
				if($diff % $notif_sched == 0 && $ended == FALSE)
				{
					$user = $this->Respondent->getUserData($notify[$i]['survey_id']);
					
					$config = Array(
						  'protocol' => 'smtp',
						  'smtp_host' => 'ssl://smtp.googlemail.com',
						  'smtp_port' => 465,
						  'esmtp_user' => 'pollwatcher.god@gmail.com',
						  'smtp_pass' => 'ichigokurakurasakiU',
						);
					$this->load->library('email', $config);
					$this->email->set_newline("\r\n");

					$this->email->from('pollwatcher.god@gmail.com', 'PollWatcher');
					$this->email->to($notify[$i]['email']);
					
					$this->email->subject($user['firstname']." ".$user['lastname']." reminds you to answer ".($user['gender']=="Male" ? "his" : "her")." survey");
					
					$notify[$i]['notif_body'] = $this->Respondent->getNotificationBody($notify[$i]['survey_id']);
					
					$this->email->message($this->load->view('notification', $notify[$i], TRUE));
				
					if (!$this->email->send())
						show_error($this->email->print_debugger());
					
				}		
				
								
			}
		}  
		
		/*
		 * Checks if an invite has been already sent to a respondent
		 *
		 * Parameter:
		 * none	
		 * 
		 * Return Value:
		 * true if the invites are valid, false otherwise
		 */		
		function already_sent()
		{
			$error = true;
			$error_message = "";
			$emails = explode(",", $this->input->post('invite_resp'));	
			foreach($emails as $email)
			{
				$temp = array( array( 'column' => 'email','value'=>trim($email) ), array( 'column' => 'survey_id', 'value' => $this->input->post('survey_id')));
				
				if($this->Respondent->exists('invitation',$temp))
				{
					$error = false;
					$error_message = $error_message."Already sent invite to ".$email."<br/>";
				}
			}
			
			if($error == false)
			{
				$error_message = $error_message."Remove email/s above from the list to proceed<br/>";
			}
			$this->validation->set_message('already_sent', $error_message);
			return $error;
		}
	}
?>
